package com.party.jackclientandroid.ui_mine.partner_center;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ocnyang.pagetransformerhelp.cardtransformer.AlphaAndScalePageTransformer;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.adapter.VipPagerAdapter;
import com.party.jackclientandroid.api.CouponService;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.VipService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.PayResult;
import com.party.jackclientandroid.bean.User;
import com.party.jackclientandroid.bean.VipBean;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.controller.PayController;
import com.party.jackclientandroid.event.PayResultEvent;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.DiscountPayBillActivity;
import com.party.jackclientandroid.ui_mine.PurchaseMembershipActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的-合伙人中心
 */
public class VipCenterActivity extends BaseActivityTitle {
    @BindView(R.id.cardViewPager)
    ViewPager mViewPager;
    @BindView(R.id.vip_status_img_btn)
    Button vipStatusBtn;
    @BindView(R.id.one_level_count_tv)
    TextView oneLevelCountTv;
    @BindView(R.id.two_level_count_tv)
    TextView twoLevelCountTv;
    @BindView(R.id.whole_layout)
    LinearLayout whole_layout;
    @BindView(R.id.test)
    TextView test;
    @BindView(R.id.wv_partner_center)
    WebView wvPartnerCenter;
    @BindView(R.id.tv_pc_div)
    TextView tvPcDiv;
    private int userRoleId, ONE_LEVEL = 1, TWO_LEVEL = 2, currChooseRolePosition = 0;
    private VipPagerAdapter myPagerAdapter;
    private VipService vipService;
    private List<VipBean> vipBeanList = new ArrayList<>();
    private PayController payController;
    private String orderId;
    private static final String TAG = "PartnerCenterActivity";
    private CouponService couponService;
    private double setBuyPrice;
    private String url;
    private WebSettings settings;
    private List<VipBean.ResponsesBean> data;
    private String parentPhone;
    private String role;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_partner_center);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initData();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    protected void initData() {
        setMiddleText("合伙人中心");
        data = new ArrayList<>();
        couponService = new CouponService(this);
        payController = new PayController(this, vipStatusBtn);
        vipService = new VipService(this);
        helper = new LoadViewHelper(test);

//        url = "https://pdkj.oss-cn-beijing.aliyuncs.com/Notice/PartnerRules.html";
//        settings = wvPartnerCenter.getSettings();
//        settings.setLoadWithOverviewMode(true);
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT); //如果我们应用程序没有设置任何cachemode，这个是默认的cache方式。 加载一张网页会检查是否有cache，如果有并且没有过期则使用本地cache，否则从网络上获取。
//        settings.setJavaScriptEnabled(true); //启动js功能  (json)
//        settings.setBuiltInZoomControls(true); //显示放大缩小按钮(不支持已经适配好移动端的页面)
//        settings.setUseWideViewPort(true); //双击缩放(不支持已经适配好移动端的页面)
//        wvPartnerCenter.setHorizontalScrollBarEnabled(false);//水平不显示
//        wvPartnerCenter.setVerticalScrollBarEnabled(false); //垂直不显示
//        wvPartnerCenter.loadUrl(url);

        myPagerAdapter = new VipPagerAdapter(data, (BaseActivity) mActivity);
        mViewPager.setAdapter(myPagerAdapter);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setPageMargin(40);
        mViewPager.setPageTransformer(true, new AlphaAndScalePageTransformer());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                checkBtn(position, data);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        addDisposableIoMain(vipService.getSubUserCount(ONE_LEVEL), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> baseBean) {
                oneLevelCountTv.setText(baseBean.getData().getCount() + "人");
                addDisposableIoMain(vipService.getSubUserCount(TWO_LEVEL), new DefaultConsumer<CommonResult>(mApplication) {
                    @Override
                    public void operateSuccess(BaseResult<CommonResult> baseBean) {
                        twoLevelCountTv.setText(baseBean.getData().getCount() + "人");
                        helper.showContent();
                    }
                });
            }
        });
        userRoleId = mApplication.getUser().getRoleId();
        getNeedData();
    }

    /**
     * 获取数据
     */
    private void getNeedData() {
        addDisposableIoMain(vipService.getVipData(), new DefaultConsumer<VipBean>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<VipBean> baseBean) {
                parentPhone = baseBean.getData().getParentPhone();
                role = baseBean.getData().getRole();
                tvPcDiv.setText(Html.fromHtml(role));
                data.clear();
                data.addAll(baseBean.getData().getResponses());
                checkBtn(currChooseRolePosition, data);

                myPagerAdapter.notifyDataSetChanged();
                mViewPager.setCurrentItem(userRoleId - 1);
            }
        });
    }

    private void checkBtn(int position, List<VipBean.ResponsesBean> vipBeanList) {
        if (vipBeanList.get(position).getId() <= userRoleId) {
            vipStatusBtn.setClickable(false);
            vipStatusBtn.setText("已开通");
        } else {
            vipStatusBtn.setText("立即开通");
            vipStatusBtn.setClickable(true);
        }
        currChooseRolePosition = position;
        orderId = null;
    }

    @OnClick({R.id.see_detail_ll, R.id.vip_status_img_btn, R.id.one_level, R.id.two_level})
    public void handleClickSth(View view) {
        switch (view.getId()) {
            case R.id.one_level:
            case R.id.two_level:
            case R.id.see_detail_ll:
                startActivity(RecommendDetailActivity.class);
                break;
            case R.id.vip_status_img_btn:
                setBuyPrice = data.get(currChooseRolePosition).getCurrentPrice();
//                submitOrder();
                Intent intent = new Intent(this, PurchaseMembershipActivity.class);
                intent.putExtra("parentPhone", parentPhone);
                intent.putExtra("id", data.get(currChooseRolePosition).getId() + "");
                intent.putExtra("name", data.get(currChooseRolePosition).getName() + "");
                intent.putExtra("currentPrice", data.get(currChooseRolePosition).getCurrentPrice() + "");
                intent.putExtra("originalPrice", data.get(currChooseRolePosition).getOriginalPrice() + "");
                intent.putExtra("setBuyPrice", setBuyPrice + "");
                intent.putExtra("currChooseRolePosition", currChooseRolePosition);
                intent.putExtra("role", role);
                startActivity(intent);
        }
    }

    int roleId;

    public void submitOrder() {
        payController.showPayMethod(setBuyPrice + "", orderId, (View v) -> {
            roleId = data.get(currChooseRolePosition).getId();
            Map<String, String> map = new HashMap();
            map.put("finalPrice", setBuyPrice + "");
            map.put("totalPrice", data.get(currChooseRolePosition).getOriginalPrice() + "");
            map.put("shopId", "666666");
            map.put("quantity", "1");// 购买数量为 1
            map.put("itemId", roleId + "");//角色id
            map.put("type", "4");//购买会员是 类型 4
            map.put("price", setBuyPrice + "");//单价
            Log.d(TAG, map.toString());
            addDisposableIoMain(couponService.submitOrder(map), new DefaultConsumer<CommonResult>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<CommonResult> result) {
                    orderId = result.getData().getId() + "";
                    payController.pay(orderId);
                }
            });
        });
        payController.setInputPassFinish(new DiscountPayBillActivity.PayCompleteListener() {
            @Override
            public void payOk(BaseResult<PayResult> result) {
                changeVipStat();
            }

            @Override
            public void payFail(String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    public void changeVipStat() {
        User user = mApplication.getUser();
        user.setRoleId(roleId);
        mApplication.setUser(user);
        String roleText = roleId == 2 ? "黄金会员" : "钻石会员";
        myPagerAdapter.notifyDataSetChanged();
        DialogController.showMustConfirmDialog(mActivity, roleText, "恭喜你成为" + roleText + "!", (View v) -> {
            finish();
        });
    }

    @Subscribe
    public void onPayResultEvent(PayResultEvent event) {
        if (event.getResultType() == 1) {
            DialogController.showMustConfirmDialog(mActivity, "购买成功", (View v) -> {
                changeVipStat();
            });
        }
    }

    @OnClick({R.id.right_btn, R.id.left_btn})
    public void scrollTo(View view) {
        switch (view.getId()) {
            case R.id.left_btn:
                if (mViewPager.getCurrentItem() >= 1)
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
                break;
            case R.id.right_btn:
                if (mViewPager.getCurrentItem() < mViewPager.getOffscreenPageLimit())
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                break;
        }
    }

    public int getUserRoleId() {
        return userRoleId;
    }

    public void setUserRoleId(int userRoleId) {
        this.userRoleId = userRoleId;
    }
}
